package com.avic.modules.quartz.utils;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.CharsetUtil;
import com.avic.utils.FileUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author ayetony.miao
 * @date 2022/7/14 16:15
 **/
public class Csv2Excel {


    public static void main(String[] args) throws Exception {
        CsvReader reader = CsvUtil.getReader();
        CsvData data = reader.read(new File("localstorage/files/instrumental.csv"), CharsetUtil.CHARSET_GBK);
        List<CsvRow> rows = data.getRows();
        // workbook object
        XSSFWorkbook workbook = new XSSFWorkbook();
        // spreadsheet object
        XSSFSheet spreadsheet = workbook.createSheet(" Data csv ");
        // creating a row object
        XSSFRow row;
        int rowid = 0;
        for (CsvRow r : rows) {
            row = spreadsheet.createRow(rowid++);
            int cellid = 0;
            System.out.println(r.getRawList());
            for (String obj : r.getRawList()) {
                Cell cell = row.createCell(cellid++);
                cell.setCellValue(obj);
            }
        }
        FileOutputStream out = new FileOutputStream(FileUtil.getName("localstorage/files/instrumental.csv") + ".xls");
        workbook.write(out);
        out.close();
    }

    public static String convert(String absoluteFilePathname) throws IOException {
        String newPath = absoluteFilePathname + ".xls";
        if(Files.exists(Paths.get(newPath))){
            return newPath;
        }
        CsvReader reader = CsvUtil.getReader();
        CsvData data = reader.read(new File(absoluteFilePathname), CharsetUtil.CHARSET_GBK);
        List<CsvRow> rows = data.getRows();

        // workbook object
        XSSFWorkbook workbook = new XSSFWorkbook();
        // spreadsheet object
        XSSFSheet spreadsheet = workbook.createSheet(" Data csv ");
        // creating a row object
        XSSFRow row;

        int rowid = 0;
        for (CsvRow r : rows) {
            row = spreadsheet.createRow(rowid++);
            int cellid = 0;
            for (String obj : r.getRawList()) {
                Cell cell = row.createCell(cellid++);
                cell.setCellValue(obj);
            }
        }
        reader.close();
        FileOutputStream out = new FileOutputStream(newPath);
        workbook.write(out);
        out.flush();
        out.close();
        return newPath;
    }



}
